<template>
<view class="page__bd">
	<custom-navbar bgColor="bg-white shadow" :isBack="false" :isHome="false">
		<block slot="content">购物车</block>
	</custom-navbar>
	
	<view class="edit-goods">
		<view>购物车共<text class="goods-num">{{siteCartItemNum}}</text>件商品<text class="margin-left-xs">重量：<text class="text-red">{{siteCartWeight}}kg</text></text></view>
		<view>
			<button class="daui-btn line-grey round" @click="editGoods" v-if="siteCartItemNum > 0">{{isEdit?"完成":"编辑商品"}}</button>
		</view>
	</view>
	
	<block v-for="(item,index) in cartGroup" :key="index" v-if="cartNum > 0">
		<evan-checkbox-group ref="cGroup" @change="onGroupChange" v-model="item.cartIds">
			<view class="daui-card daui-card__full daui-card_access daui-card_celltit cart-shop margin-top-no">
				<view class="daui-card__hd">
					<view class="daui-cell">
						<view class="daui-cell__bd" @click="openShopDetail(item.shid)">
							<text class="iconfontzz icon-ruzhu text-lg margin-right-xs"></text>{{item.shop_name}}
						</view>
						<view class="daui-cell__ft" style="display: none;">
							<view class="text-grey" data-isedit="0" @click="setOpened"><text class="iconfontzz text-lg">&#xeaa7;</text>编辑</view>
						</view>
					</view>
				</view>
				<view class="daui-card__bd J_list">
					<uni-swipe-action>
						<uni-swipe-action-item v-for="(item2,index2) in item.cartList" :key="index2" :right-options="actions" @click="bindClick" :custom="item2.id">
							<view class="daui-media daui-media_appmsg cart-list" :data-id="item2.id">
								<view class="daui-media__hd cart-check">
									<evan-checkbox :custom="item2.id" :label="item2.id" primaryColor="#eb0909" @change="onOneChange"></evan-checkbox>
								</view>
								<view class="daui-media__hd" @click="openProductDetail(item2.pid)">
									<image class="daui-media__thumb" :src="item2.logo_show" alt=""></image>
								</view>
								<view class="daui-media__bd">
									<view class="daui-media__title" @click="openProductDetail(item2.pid)">{{item2.prod_name}}</view>
									<view class="daui-media__work" v-if="item2.is_spec_open==1">
										规格：<text>{{item2.spec_1}}</text>
										<text v-if="item2.spec_2">，{{item2.spec_2}}</text>
									</view>
									<view class="daui-media__desc">
										<text>品牌：{{item2.brand_name}}</text>
										<text class="margin-left">产地：{{item2.originplace}}</text>
									</view>
									<view class="daui-media__desc">
										包装方式：<text>{{item2.package}}</text>
									</view>
									<view class="daui-media__desc">
										重量：<text>{{item2.weight}}kg</text>
									</view>
									<view class="flex margin-tb-sm cart-buynum">
										<view class="flex-sub">
											<text class="text-price text-red text-xl">{{item2.one_price}}</text>
										</view>
										<view>
											<lxc-count @handleCount="changeCartNum" :index="index" :value="item2.buy_num" :delayed="100" :customId="item2.id" costyle="1"></lxc-count>
										</view>
									</view>
								</view>
							</view>
						</uni-swipe-action-item>
					</uni-swipe-action>
				</view>
				<view class="daui-card__ft" v-if="0">
					<view class="daui-cell">
						<view class="daui-cell__hd">
							<evan-checkbox @change="selectAll" :index="index" :custom="item.shid" primaryColor="#eb0909">全选</evan-checkbox>
						</view>
						<view class="daui-cell__bd text-right margin-right-sm">
							<view v-if="!isEdit">共计：<text class="text-red text-xl">{{item.siteCartBuyNum}}</text>件 重量：<text class="text-red text-xl">{{item.siteCartBuyNum}}</text>件 合计:<text class="text-price text-red text-xl">{{item.shopCartPrice}}</text></view>
						</view>
						<view class="daui-cell__ft">
							<button class="daui-btn bg-primary" v-if="!isEdit" @click="openOrderPrepair(item.shid)">去结算</button>
							<button class="daui-btn line-red" v-else @click="doDeleteCartBatch(item.shid)">删除</button>
						</view>
					</view>
				</view>
			</view>
		</evan-checkbox-group>
	</block>
	
	<view class="daui-cell foot">
		<view class="daui-cell__hd">
			<evan-checkbox @change="selectAll" :index="0" :custom="0" primaryColor="#eb0909" :titleStyle="{'font-size':'14px'}">全选</evan-checkbox>
		</view>
		<view class="daui-cell__bd text-right margin-right-sm">
			<view v-if="!isEdit"><!--共计：<text class="text-red text-xl">{{siteCartItemNum}}</text>件--><!--重量：<text class="text-red text-xl">{{siteCartWeight}}kg</text>--><text class="margin-left-xs">合计:<text class="text-price text-red">{{siteCartPrice}}</text></text></view>
		</view>
		<view class="daui-cell__ft">
			<button class="daui-btn bg-red round" v-if="!isEdit" @click="openOrderPrepair(0)">去结算</button>
			<button class="daui-btn line-red round" v-else>删除</button>
		</view>
	</view>
	
	<view class="daui-empty" v-if="loadding == true && cartNum == 0">
		<view class="daui-empty__icon">
			<image src="https://www.uucms.com/danceui_res/empty/cart.png"></image>
		</view>
		<view class="daui-empty__bd">
			购物车空空如也
		</view>
		<view class="daui-btn bg-primary round" :hover-stay-time="150" @tap="openProductList">去逛逛</view>
	</view>
	
	<!--toast提示-->
	<daui-toast ref="toast"></daui-toast>
</view>
</template>

<script>
import danceuiTool from '../../utils/danceuiTool';
import http from "../../server/api-product.js";
import uniSwipeAction from '@/components/uni-swipe-action/uni-swipe-action';
import uniSwipeActionItem from '@/components/uni-swipe-action-item/uni-swipe-action-item';
import lxcCount from '@/components/lxc-count/lxc-count.vue';
export default {
	components: {
		uniSwipeAction,
		uniSwipeActionItem,
		lxcCount
	},
	data() {
		return {
			isBack: 0,
			cArr: [],
			moonuid: 0,
			moonInfo: {},
			colorChecked: true,
			isAll: false,
			cartNum: 0,
			siteCartItemNum: 0,
			siteCartWeight: 0,
			siteCartPrice: 0,
			totalPrice: 0,
			cartIds: [], //购物车id
			cartGroup: [],
			actions: [
				{
					text: '收藏',
					style: {
						backgroundColor: '#FFC600'
					}
				},
				{
					text: '删除',
					style: {
						backgroundColor: '#F82400'
					}
				}
			],
			actions2: [{
					name: '看相似',
					color: '#fff',
					fontsize: 28,
					width: 64,
					background: '#FF7035'
				},
				{
					name: '删除',
					color: '#fff',
					fontsize: 28,
					width: 64,
					background: '#F82400'
				}
			],
			isEdit: false,
			pageIndex: 1,
			loadding: false,
			pullUpOn: true
		}
	},
	// watch: {
	// 	cArr: {
	// 		immediate: true,
	// 		deep: true,
	// 		handler(value) {
	// 			console.log('value:', value);
	// 			//this.currentValue = value || []
	// 			//this.deepSetValue(this.$children)
	// 		}
	// 	}
	// },
	onLoad(options) {
		console.log('onLoad的参数:', options);
	},
	onShow() {
		this.getData();
	},
	onBackPress(options) {
		console.log('from:' + options.from)
	},
	filters: {
		getPrice(price) {
			price = price || 0;
			return price.toFixed(2)
		}
	},
	onPullDownRefresh(){
		console.log('=====上拉刷新refresh');
		this.list_param = {...this.list_param,p:1}
		this.getData();
		setTimeout(() => {
			uni.stopPullDownRefresh()
		}, 200);
	},
	// onNavigationBarButtonTap(e) {
	// 	this.isEdit = !this.isEdit;
	// 	let text = this.isEdit ? "完成" : "编辑";
	// 	// #ifdef APP-PLUS
	// 	let webView = this.$mp.page.$getAppWebview();
	// 	webView.setTitleNViewButtonStyle(0, {
	// 		text: text
	// 	});
	// 	// #endif
	// },
	methods: {
		async getData(){ //请求并获取数据
			const token = uni.getStorageSync('token');
			let headers = {"Authorization":"Bearer "+token};
			let ret = await http.cart(this.$refs.toast, {}, headers);
			console.log('cart页面，获取到的数据：', ret);
			if(ret.code == 200){
				var retData = ret.data;
				this.cartNum = retData.cartNum;
				this.cartGroup = retData.cartGroup;
				this.siteCartItemNum = retData.siteCartItemNum;
				this.siteCartWeight = retData.siteCartWeight;
				this.siteCartPrice = retData.siteCartPrice;
				this.loadding = true;
			}
		},
		BackPage() {
			uni.switchTab({
				url: '/pages/index/index'
			});
		},
		setOpened() {
			if (this.isOpened === 'none') {
				this.isOpened = 'left';
				return;
			}
			if (this.isOpened === 'left') {
				this.isOpened = 'right';
				return;
			}
			if (this.isOpened === 'right') {
				this.isOpened = 'none';
				return;
			}
		},
		bindClick(e) {
			var that = this;
			console.log('点击位置:'+e.position+';按钮名称:'+e.content.text+';索引:'+e.index+';自定义:'+e.custom);
			if(e.index == 0){
			}else if(e.index == 1){
				uni.showModal({
					title: '提示',
					content: '确认删除该商品吗？',
					success: function (res) {
						if (res.confirm) {
							that.doDeleteCartInfo(e.custom);
						} else if (res.cancel) {
							console.log('用户点击取消');
						}
					}
				});
			}
		},
		async doDeleteCartInfo(id){
			const token = uni.getStorageSync('token');
			let headers = {"Authorization":"Bearer "+token};
			var param = {
				id: id
			};
			let ret = await http.doDeleteCartInfo(this.$refs.toast, param, headers);
			var retData = ret.data;
			console.log('请求数据：', retData);
			//this.cartGroup[e.index].cartList[e.custom].buy_num = e.value
			this.getData();
		},
		doDeleteCartBatch(shid){ //批量删除购物车商品
			var that = this;
			uni.showModal({
				title: '提示',
				content: '确认删除选中商品吗？',
				success: function (res) {
					if (res.confirm) {
						that.doDeleteCartBatchTwo(shid);
					} else if (res.cancel) {
						console.log('用户点击取消');
					}
				}
			});
		},
		async doDeleteCartBatchTwo(shid){
			const token = uni.getStorageSync('token');
			let headers = {"Authorization":"Bearer "+token};
			var param = {
				shid: shid
			};
			let ret = await http.doDeleteCartInfo(this.$refs.toast, param, headers);
			var retData = ret.data;
			console.log('请求数据：', retData);
			//this.cartGroup[e.index].cartList[e.custom].buy_num = e.value
			this.getData();
		},
		calcHandle(){
			let buyNum = 0;
			let totalPrice = 0;
			let selectedNum = 0;
			this.dataList.map((item) => {
				if (item.selected) {
					buyNum += item.buyNum;
					totalPrice += item.price * item.buyNum;
					selectedNum++
				}
			})
			this.isAll = selectedNum === this.dataList.length
			this.buyNum = buyNum
			this.totalPrice = totalPrice
		},
		async changeCartNum(realvalue, index, custom) {
			console.log('changeCartNum操作,realvalue:'+realvalue+';index:'+index+';custom:'+custom);
			this.numberValue = realvalue;
			// this.dataList[e.index].buyNum = e.value
			// setTimeout(() => {
			// 	this.calcHandle()
			// }, 0)
			const token = uni.getStorageSync('token');
			let headers = {"Authorization":"Bearer "+token};
			var param = {
				cartId: custom,
				buyOrAdd: 1,
				initBuyNum: realvalue
			};
			let ret = await http.doAddAndUpdateCart(this.$refs.toast, param, headers);
			console.log('doAddAndUpdateCart操作，请求数据：', ret);
			if(ret.code == 200){
				var retData = ret.data;
				this.cartGroup[index].cartList[custom].buy_num = realvalue;
				//this.cartGroup[index].siteCartBuyNum = retData.siteCartBuyNum;
				//this.cartGroup[index].siteCartPrice = retData.siteCartPrice;
				this.siteCartItemNum = retData.siteCartItemNum;
				this.siteCartWeight = retData.siteCartWeight;
				this.siteCartPrice = retData.siteCartPrice;
			}
		},
		editGoods: function() {
			// #ifdef H5 || MP
			this.isEdit = !this.isEdit;
			// #endif
		},
		onGroupChange(cardIds) {
			console.log('cardIds:', cardIds);
			// var cartIds = e.detail.value;
			// console.log('cartIds:', cartIds);
			// for (var i = 0, lenI = items.length; i < lenI; ++i) {
			// 	const item = items[i]
			// 	if(values.includes(item.value)){
			// 		this.$set(item,'checked',true)
			// 	}else{
			// 		this.$set(item,'checked',false)
			// 	}
			// }
			// this.dataList.map(item => {
			// 	//如果购物车id为数字统一转成字符串
			// 	if (~this.cartIds.indexOf(item.id)) {
			// 		item.selected = true;
			// 	} else {
			// 		item.selected = false;
			// 	}
			// })
			// setTimeout(() => {
			// 	this.calcHandle()
			// }, 0)
		},
		async onOneChange(currentValue, index, custom){
			console.log('=====currentValue:', currentValue);
			console.log('参数custom:', custom);
			//获取用户登陆信息
			const token = uni.getStorageSync('token');
			let headers = {"Authorization":"Bearer "+token};
			var flag;
			if(currentValue == true){
				flag = 1;
			}else{
				flag = 2;
			}
			var param = {
				id: custom,
				flag: flag
			};
			let ret = await http.doIsCartpro(this.$refs.toast, param, headers);
		},
		async selectAll(currentValue, index, custom) {
			//console.log('=====当前页面的refs', this.$refs)
			console.log('=====currentValue:', currentValue);
			console.log('参数index:', index);
			console.log('参数custom:', custom);
			console.log('当前group选中值:', this.cArr);
			//获取用户登陆信息
			const token = uni.getStorageSync('token');
			let headers = {"Authorization":"Bearer "+token};
			var flag;
			if(currentValue == true) {
				this.$refs.cGroup[index].selectAll()
				flag = 1;
			}else{
				this.$refs.cGroup[index].clearAll()
				flag = 2;
			}
			var param = {
				shid: custom,
				flag: flag
			};
			let ret = await http.doAllCart(this.$refs.toast, param, headers);
			var retData = ret.data;
		},
		checkAll(e) {
			this.isAll = !this.isAll;
			let buyNum = 0;
			let totalPrice = 0;
			this.dataList.map((item) => {
				item.selected = this.isAll;
				if (this.isAll) {
					buyNum += item.buyNum;
					totalPrice += item.price * item.buyNum;
				}
			})
			this.totalPrice = totalPrice;
			this.buyNum = buyNum;
		},
		async openOrderPrepair() {
			//获取用户登陆信息
			const token = uni.getStorageSync('token');
			let headers = {"Authorization":"Bearer "+token};
			let ret = await http.doVerify(this.$refs.toast, {}, headers);
			if(ret.code == 200){
				var retData = ret.data;
				uni.navigateTo({
					url: '/pages/order/orderPrepair'
				})
			}
		},
		openShopDetail(shid) {
			uni.navigateTo({
				url: '/pages/shop/shopDetail?shid='+shid
			})
		},
		openProductDetail(pid) {
			uni.navigateTo({
				url: '/pages/product/productDetail?pid='+pid
			})
		},
		openProductList() {
			uni.navigateTo({
				url: '/pages/product/productList'
			})
		},
	}
}
</script>

<style>

.edit-goods{width:100%;border-radius:12rpx;overflow:hidden;padding:24rpx 30rpx 20rpx 30rpx;box-sizing:border-box;display:flex;justify-content:space-between;align-items:center;color:#333;font-size:28rpx}
.goods-num{font-weight:bold;color:#e41f19}
.evan-checkbox-group{margin-bottom:20rpx}

.daui-cell.foot{position:fixed;width:100%;bottom:90rpx}
.daui-cell.foot .evan-checkbox__label{font-size: 28rpx;}

</style>
